//
//  KLModelListViewController.m
//  Meboo
//
//  Created by kyo on 2023/12/27.
//

#import "KLModelListViewController.h"
#import "NSModelListCell.h"
//#import "KLPaymentManager.h"
#import "KLModelDetailViewController.h"
#import "KLVipViewController.h"
#import "MBRefreshGifHeaderLottie.h"
#import "MBChatListViewController.h"
#import "MBModelDataTool.h"
#import "MBWLMTopicModel.h"
@interface KLModelListViewController ()
<
UICollectionViewDelegate,
UICollectionViewDataSource
>
@property (nonatomic, strong) UIImageView *backImageView;
@property (nonatomic , strong) MBRefreshGifHeaderLottie *refreshGifHeaderLottie;
@property(nonatomic,strong) UILabel *titleLab;
@property(nonatomic,strong) UILabel *subTitleLab;
@property (nonatomic , strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIButton *messageBtn;
@property (nonatomic , assign) NSInteger clickNum;

@property (nonatomic, strong) UIButton *vipNoticeBtn;
@end

@implementation KLModelListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = HEXS(@"ffffff");
    self.navigationController.navigationBarHidden = YES;
    [self setupUI];
    [self getdata];
    [MBNotificationCenter addObserver:self selector:@selector(updatLikePass:) name:MODEL_DETAIL_CLICK_LIKEPASS object:nil];
    __WeakSelf
    [self.refreshGifHeaderLottie setJsonName:@"refresh.json"];
        self.collectionView.mj_header = self.refreshGifHeaderLottie;
    
    [self.refreshGifHeaderLottie setRefreshingBlock:^{
        MBUserAccount *account = [MBUserAccount defaultAccount];
        if (!account.isVip) {
            if (![account.todayStr isEqualToString:[weakSelf getTodayStr]]) {
                account.todayStr = [weakSelf getTodayStr];
                account.modelListRefreshNum = 0;
                weakSelf.vipNoticeBtn.hidden = YES;
            }
            
            if (account.modelListRefreshNum == 2) {
                [weakSelf.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.top.equalTo(weakSelf.subTitleLab.mas_bottom).offset(MBHeightScale(56));
                }];
                weakSelf.vipNoticeBtn.hidden = NO;
            }
            account.modelListRefreshNum++;
            [MBUserAccount saveAccount:account];
            [weakSelf.collectionView.mj_header endRefreshing];
        }
        [weakSelf getdata];
    }];
    
    [self getRongCloudToken];
}

#pragma mark - Private Method
- (void)getRongCloudToken {
    __WeakSelf
    [[MBChatDataManager sharedManager] getRongCloudToken:^(BOOL success) {
        if (success) {
            [weakSelf getRongCloudConnectState];
        }
    }];
}

- (void)getRongCloudConnectState {
//    __WeakSelf
    [[RCIM sharedRCIM] connectWithToken:[MBUserAccount defaultAccount].rongCloudToken
                               dbOpened:^(RCDBErrorCode code) {
        //消息数据库打开，可以进入到主页面
    } success:^(NSString *userId) {
        //连接成功,可跳转至会话列表页
        //存储本人的userid
        MBUserAccount  *account = [MBUserAccount defaultAccount];
        account.chatUserId = userId;
        [MBUserAccount  saveAccount:account];
    }error:^(RCConnectErrorCode status) {
        if (status == RC_CONN_TOKEN_INCORRECT) {
            //从 APP 服务获取新 token，并重连
            NSLog(@"");
        } else {
            //无法连接到 IM 服务器，请根据相应的错误码作出对应处理
            NSLog(@"");
        }
    }];
}


- (void)getdata {
    __WeakSelf
    [[MBWhoLikeMeDataManager sharedManager] getHomePageList:^(BOOL success) {
        if (success && [MBWhoLikeMeDataManager sharedManager].topicDataArr.count > 0) {
            [[MBModelDataTool sharedTool] getDictArr];
            [weakSelf.collectionView reloadData];
        }
        [self.collectionView.mj_header endRefreshing];
    }];
}

- (void)updatLikePass:(NSNotification*)notification {
    NSString *stateStr = [notification object];
    MBWLMTopicModel *model = [MBWhoLikeMeDataManager sharedManager].topicDataArr[self.clickNum];
    model.likePassState = [stateStr integerValue];
    [[MBWhoLikeMeDataManager sharedManager].topicDataArr replaceObjectAtIndex:self.clickNum withObject:model];
}

- (NSString *)getTodayStr {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"]; // 设置日期格式
    NSDate *today = [NSDate date]; // 获取当前日期
    NSString *dateString = [formatter stringFromDate:today];
    return dateString;
}

#pragma mark - Action

- (void)vipAction {
    [self.navigationController pushViewController:[KLVipViewController new] animated:YES];
}

- (void)messageAction {
    NSArray *displayConversationTypeArray = @[@(ConversationType_PRIVATE)];
    MBChatListViewController *conversationListVC = [[MBChatListViewController alloc] initWithDisplayConversationTypes:displayConversationTypeArray
                                                                                           collectionConversationType:nil];
    [conversationListVC setConversationAvatarStyle:RC_USER_AVATAR_CYCLE];
    [self.navigationController pushViewController:conversationListVC animated:YES];
}

#pragma mark -- collectionView  delegate datasource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [MBWhoLikeMeDataManager sharedManager].topicDataArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSModelListCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"NSModelListCell" forIndexPath:indexPath];
    cell.model = [MBWhoLikeMeDataManager sharedManager].topicDataArr[indexPath.row];
    cell.tagStr = [[MBModelDataTool sharedTool] getTagString];
    if (indexPath.row > 31) {
        cell.dict = [MBModelDataTool sharedTool].dictArr.lastObject;
    } else {
        cell.dict = [MBModelDataTool sharedTool].dictArr[indexPath.row];
    }
    
    return cell;
}

//设置每个section的UIEdgeInsets
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(MBHeightScale(10), MBWidthScale(0), MBHeightScale(10), MBWidthScale(0));
}

//设置列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return MBHeightScale(15);
}

//设置每个item水平间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return MBWidthScale(0);
}

//定义每一个cell的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(ScreenWidth-MBWidthScale(40), MBHeightScale(195));
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *dict = [NSDictionary dictionary];
    if (indexPath.row > 31) {
        dict = [MBModelDataTool sharedTool].dictArr.lastObject;
    } else {
        dict = [MBModelDataTool sharedTool].dictArr[indexPath.row];
    }
    
    self.clickNum = indexPath.row;
    KLModelDetailViewController *detailVc = [KLModelDetailViewController new];
    detailVc.model = [MBWhoLikeMeDataManager sharedManager].topicDataArr[indexPath.row];
    detailVc.subStr = [NSString stringWithFormat:@"%@",dict[@"title"]];
    [self.navigationController pushViewController:detailVc animated:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (![MBUserAccount defaultAccount].isVip) {
        if ([[MBUserAccount defaultAccount].todayStr isEqualToString:[self getTodayStr]] && [MBUserAccount defaultAccount].modelListRefreshNum >= 3) {
            if (scrollView.contentOffset.y <= 0) {
                [scrollView setContentOffset:CGPointMake(scrollView.contentOffset.x, 0)];
            }
        }
    }
}

#pragma mark - UI
- (void)setupUI {
    
    [self.view addSubview:self.backImageView];
    [self.backImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    [self.view addSubview:self.titleLab];
    [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(StatusBarHeight+MBHeightScale(9));
        make.left.mas_equalTo(MBWidthScale(24));
    }];
    
    [self.view addSubview:self.subTitleLab];
    [self.subTitleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLab.mas_bottom).offset(MBHeightScale(10));
        make.left.mas_equalTo(MBWidthScale(24));
    }];
    
    [self.view addSubview:self.messageBtn];
    [self.messageBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.titleLab);
        make.right.mas_equalTo(MBWidthScale(-20));
//        make.width.mas_equalTo(MBWidthScale(37));
//        make.height.mas_equalTo(MBHeightScale(26));
    }];
    
    [self.view addSubview:self.collectionView];
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.subTitleLab.mas_bottom).offset(MBHeightScale(10));
        make.left.right.bottom.equalTo(self.view);
    }];
    
    [self.view addSubview:self.vipNoticeBtn];
    [self.vipNoticeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.subTitleLab.mas_bottom).offset(MBHeightScale(28));
    }];
    
    if ([[MBUserAccount defaultAccount].todayStr isEqualToString:[self getTodayStr]] && [MBUserAccount defaultAccount].modelListRefreshNum >= 3) {
        [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.subTitleLab.mas_bottom).offset(MBHeightScale(56));
        }];
        self.vipNoticeBtn.hidden = NO;
    }

}

#pragma mark - Setter && Getter
- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [UILabel new];
        _titleLab.text = @"Fashion\nInformation";
        _titleLab.font = PDBoldScale(36);
        _titleLab.numberOfLines = 2;
        _titleLab.textColor = HEXS(@"3D2D2C");
    }
    return _titleLab;
}

- (UILabel *)subTitleLab {
    if (!_subTitleLab) {
        _subTitleLab = [UILabel new];
        _subTitleLab.text = @"Continuously updating...";
        _subTitleLab.font = PDMediumScale(14);
        _subTitleLab.textColor = HEXS(@"999999");
    }
    return _subTitleLab;
}

- (UICollectionView *)collectionView {
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = UIColor.clearColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        [_collectionView registerClass:[NSModelListCell class] forCellWithReuseIdentifier:@"NSModelListCell"];
    }
    return _collectionView;
}

- (MBRefreshGifHeaderLottie *)refreshGifHeaderLottie {
    if (!_refreshGifHeaderLottie) {
        _refreshGifHeaderLottie = [MBRefreshGifHeaderLottie new];
    }
    return _refreshGifHeaderLottie;
}

- (UIButton *)messageBtn {
    if (!_messageBtn) {
        _messageBtn = [[UIButton alloc] init];
        [_messageBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        [_messageBtn setBackgroundImage:ImageWithName(@"common_chat") forState:0];
        [_messageBtn addTarget:self action:@selector(messageAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _messageBtn;
}

- (UIButton *)vipNoticeBtn {
    if (!_vipNoticeBtn) {
        _vipNoticeBtn = [[UIButton alloc] init];
        _vipNoticeBtn.hidden = YES;
        [_vipNoticeBtn setYXEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
        _vipNoticeBtn.titleLabel.font = PDMediumScale(14);
        [_vipNoticeBtn setTitle:@"Today's refresh limit has been reached." forState:0];
        [_vipNoticeBtn setTitleColor:[UIColor colorWithRed:185 / 255.0 green:33 / 255.0 blue:118 / 255.0 alpha:0.6] forState:0];
        [_vipNoticeBtn addTarget:self action:@selector(vipAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _vipNoticeBtn;
}

- (UIImageView *)backImageView {
    if (!_backImageView) {
        _backImageView = [UIImageView new];
        _backImageView.image = ImageWithName(@"home_back_image");
    }
    return _backImageView;
}
@end
